<?php

/*
 * This will be the Edit Department page. 
 * 
 * Created by: Peter Agno Jr.
 * Date created: November 23, 2011
 */

    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // Get the data from post
    $deptPosId = $_POST['deptPosId'];
    
    // Get deptPosId details
    $query =
        "
            SELECT D.departmentId as departmentId, D.departmentName as departmentName, P.positionId as positionId, P.positionName as positionName
            FROM Department_Position as DP, Department as D, Position as P
            WHERE DP.deptPosId = '$deptPosId' AND DP.departmentId = D.departmentId AND DP.positionId = P.positionId
        ";

    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    $departmentId = $row['departmentId'];
    $departmentName = $row['departmentName'];
    $positionId = $row['positionId'];
    $positionName = $row['positionName'];

?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){ 
            var rowSecGrp = 0; // variable for the number of total security groups of the position
            
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#adminTools-nav").addClass("highlightMenuBar");
            jQuery("#orgSetup-nav").addClass("highlightMenuBar");
            jQuery("#posSetup-nav").addClass("highlightMenuBar");
            
            addSecGroupRows();
                       
            // Start - Add another row in Position's Security Group Screenlet
            jQuery('#addSecGrpBtn').live("click",function() {
                addPosSecGrpRow();
            }); // End - Add another row in Position's Security Group Screenlet
            
            // Start - Remove a security group row
            jQuery('.removeSecGrpBtn').live("click",function() {
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                jQuery("#rowSecGrpId_"+tempSubstr[1]).remove();
                
                // Add a department row if the table row is equal to 1 (header's row)
                if ( jQuery('#posSecGrpTable tr').length == 2 ) {
                    jQuery("#addSecGrpBtn").click();
                }
            }); // End - Remove a security group row
            
            // Start - Go back to admPositionSetup.php
            jQuery('#admPosStpBtn').live("click",function() {
                window.location = 'admDeptPosSetup.php';
            }); // End - Go back to admPositionSetup.php
            
            // Start - edit position
            jQuery('#editPosButton').live("click",function() {
                if ( jQuery("#positionName").val() == "" ) {
                    // Show error message if the user clicked the edit button
                    // but haven't inputted all of the neccessary information.
                    alert("Please input the required information.");
                }
                else if ( noSameSecGrp() != true ) {
                    alert("Error : There should be no same security group.");
                }
                else {
                    var secGrpIds = "";
                    // Get each of the value of secGrpId
                    jQuery('.secGrpId').each(function(index) {
                        secGrpIds += jQuery('#' + this.id).val() + ",";
                    });
                    
                    // Start - Ajax the editing of position
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admEditPos.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            deptPosId : jQuery("#deptPosId").val(),
                            positionName : jQuery("#positionName").val(),
                            secGrpIds : secGrpIds
                        },
                        success : function(data){
                            // If, successful editing of position
                            if (data) {
                                if ( data[0].flag == "success" ) {
                                    jQuery("#deptPosSuccessMessage").val(data[0].msg);
                                    jQuery("#deptPosStpMsgForm").submit();
                                }
                                else {
                                    alert(data[0].msg);
                                }
                            } // End if, successful editing of position
                        },
                        error : function() {
                            alert("Error : Editing the position was not successful.");
                        }
                    }); // End - Ajax the editing of position
                } // End else
            }); // End - edit position
            
            // Start - Function: Check if there is same security group in Position's Security Group Screenlet
            function noSameSecGrp() {
                noSame = true;
                
                if ( jQuery('#posSecGrpTable tr').length == 3 ) {
                    return noSame;
                }
                else {
                    for( x = 1 ; x <= rowSecGrp && noSame == true ; x++ ){
                        for( y = 1 ; y <= rowSecGrp && noSame == true ; y++ ){
                            if ( x != y ) {
                                if ( jQuery("#secGrpId_"+x).val() == jQuery("#secGrpId_"+y).val() && jQuery("#secGrpId_"+x).val() != undefined && jQuery("#secGrpId_"+y).val() != undefined  ) {
                                    noSame = false;
                                }
                            }
                        }
                    }
                    
                    return noSame;
                }
            } // End - Function: Check if there is same security group in Position's Security Group Screenlet
            
            // Start - Add n number of rows of addPosSecGrpRow()
            function addSecGroupRows() {
                var x = 0;
                x = parseInt(x);
                y = parseInt(jQuery("#secGrpNumRows").val());
                
                for ( ; x < y ; x++ ) {
                    addPosSecGrpRow();
                }
                
                adjustSecGrp(y);
            } // End - Add n number of rows of addPosSecGrpRow()
            
            // Start - Adjust the value of the dropdown of the security groups
            function adjustSecGrp(numSecGrpRows) {
                var theSecGrps = jQuery("#theSecGrps").val();
                tempSecGrps = theSecGrps.split(',');
                
                for ( x = 0 ; x < numSecGrpRows ; x++ ) {
                    jQuery("#secGrpId_"+ (x+1)).val(tempSecGrps[x]);
                }
            } // End - Adjust the value of the dropdown of the security groups
            
            // Start - Function: Add another row in Position's Security Group Screenlet
            function addPosSecGrpRow() {
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getSecGroupList.php',
                    dataType : 'json',
                    async : false,
                    data: {
                    },
                    success : function(data){
                        if (data) {
                            secGrpRow = "";
                            rowSecGrp++;
                            secGrpRow += "<tr id='rowSecGrpId_"+rowSecGrp+"'>";

                            // Prepare the Security Group dropdown
                            secGrpRow += "<td><select name='secGrpId' id='secGrpId_"+rowSecGrp+"' class='secGrpId'>";
                                
                            jQuery.each(data, function(index, data) {
                                secGrpRow += "<option value='"+data.securityGroupId+"'>"+data.securityGroupName+"</option>";
                            });
                            
                            secGrpRow += "</select></td>";    // Close the Security Group dropdown
                                
                            // Prepare the Remove button
                            secGrpRow += "<td style='text-align:center;'><img src='images/ximage.png' height='20px' width='20px' style='cursor: pointer;' name='removeSecGrpBtn' id='removeSecGrpBtn_"+rowSecGrp+"'class='removeSecGrpBtn'/>";
                            secGrpRow += "</tr>"; // Close the row
                            jQuery(".secGrpAddRow").before(secGrpRow);    // Append the row
                        } 
                    },
                    error : function() {
                        alert("Error : Adding security group row was not successful.");
                    }
                });
            } // End - Function: Add another row in Position's Security Group Screenlet
            
        }); // End - jQuery document ready
    </script>
<!-- HEAD END -->

<div id="content">
<h1>Edit Position</h1>
    <div class="contentbox">       
        <?php
        // Check permission
        $thePermissions = array('POSSTP');
        if ( checkPermission( $thePermissions, $userId ) == true ) {
        ?>
            <span class="screenlet" >Position Information</span>
            <table>
                <tr>
                    <td>Department Name : </td>
                    <td>
                        <input type="hidden" name="deptPosId" id="deptPosId" value="<?php echo $deptPosId; ?>"/>
                        <input type="hidden" name="departmentId" id="departmentId" value="<?php echo $departmentId; ?>"/>
                        <input type="hidden" name="departmentName" id="departmentName" value="<?php echo $departmentName; ?>"/>
                        <?php echo $departmentName; ?>
                    </td>
                </tr> 
                <tr>
                    <td>Position ID : </td>
                    <td>
                        <input type="hidden" name="positionId" id="positionId" value="<?php echo $positionId; ?>"/>
                        <?php echo $positionId; ?>
                    </td>
                </tr>
                <tr>
                    <td>Position Name : </td>
                    <td>
                        <input type="text" name="positionName" id="positionName" value="<?php echo $positionName; ?>"/>
                    </td>
                </tr>
            </table>
            
            <!-- POSITION SECURITY GROUPS -->
            <span class="screenlet" >Select Security Groups</span>
            <table border="1" id="posSecGrpTable">
                <tr>
                    <th>Security Group Name</th>
                    <th>Action</th>
                </tr>
                <tr class="secGrpAddRow">
                    <th></th>
                    <th><input type="Submit" name="addSecGrpBtn" id="addSecGrpBtn" value="Add" class="siteGreenButton" /></th>
                </tr>
            </table>
            
            <?php
                // Add the number of Security Groups
                // Get the security groups and its number
                $secGrpQuery =
                    "
                        SELECT SG.securityGroupId as securityGroupId, SG.securityGroupName as securityGroupName
                        FROM Dept_Pos_SecurityGroup as DPSG, SecurityGroup as SG
                        WHERE DPSG.deptPosId = '$deptPosId' AND DPSG.securityGroupId = SG.securityGroupId
                    ";

                $secGrpResult = mysql_query($secGrpQuery) or die ('Error in query: $secGrpQuery. ' . mysql_error());
                $secGrpNumRows = mysql_num_rows($secGrpResult);
                
                $theSecGrps = "";
                while ( $secGrpRow = mysql_fetch_array($secGrpResult) ) {
                    $theSecGrps = $theSecGrps . $secGrpRow['securityGroupId'] . ",";
                }
                mysql_free_result($secGrpResult);
            ?>
            <input type="hidden" name="theSecGrps" id="theSecGrps" value="<?php echo $theSecGrps;?>" />
            <input type="hidden" name="secGrpNumRows" id="secGrpNumRows" value="<?php echo $secGrpNumRows;?>" />
            
            <input type="Submit" name="editPosButton" id="editPosButton" value="Edit" class="siteGreenButton" />
            
            <!-- Display cancel button -->
            <input type="Submit" name="admPosStpBtn" id="admPosStpBtn" value="Cancel" class="siteRedButton" />
        
            <!-- Hidden form to be used when the editing of position was successful -->
            <form id="deptPosStpMsgForm" name="deptPosStpMsgForm" action="admDeptPosSetup.php" method="POST">
                <input type="hidden" name="deptPosSuccessMessage" id="deptPosSuccessMessage" value=""/>
            </form>
        <?php
            mysql_free_result($result);
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div> <!-- contentbox end div -->
    <div style="position:relative; visibility: hidden">end</div>    <!-- extra space for contentbox -->
</div> <!-- content end div -->
<?php
    include ("siteBottom.php"); 
?>

